import os
import logging
import traceback
import subprocess

from tool_util import get_mongo_resource_info
from tool_util import prometheus_push

from info_config import prometheus_url
from info_config import mongo_operation_metrics_name
from info_config import db_user
from info_config import db_password
from info_config import mongostat_path

# Get the current script path
script_path = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_path, "mongo_operation_monitor_all.log")

logging.basicConfig(
    filename=log_file,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


def get_mongo_read_write_queue_time(mongo_host, mongo_port):
    try:
        # Define the mongostat command with the required arguments
        command = [
            f"{mongostat_path}/mongostat",
            # "/opt/gaorb/mongodb-database-tools-ubuntu2004-x86_64-100.6.1/bin/mongostat",
            "-u", db_user,
            "--password", db_password,
            "--host", f"{mongo_host}:{mongo_port}",
            "--authenticationDatabase", "admin",
            "--rowcount", "1",
            "-o", "qrw,arw",
            "--noheaders"
        ]
        
        # Execute the command and capture the output
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        output = result.stdout.strip()

        # Parse the output to get qr, qw, ar, and aw values
        qrw, arw = output.split(" ")
        qr, qw = map(int, qrw.split("|"))
        ar, aw = map(int, arw.split("|"))

        # Return the parsed values in a dictionary
        return {"qr": qr, "qw": qw, "ar": ar, "aw": aw}
    except Exception as e:
        logging.error(f"Error running mongostat: {e}")
        traceback.print_exc()
        # Return zeroed values if there is an error
        return None

def mongo_response_monitor(mongo_info):
    """Monitors the PostgreSQL instance for response time on a specific large table."""
    id = mongo_info[0]
    name = mongo_info[1]
    mongo_host = mongo_info[2].get("host")
    mongo_port = mongo_info[2].get("port")
    role = mongo_info[3]
    oper = get_mongo_read_write_queue_time(mongo_host, mongo_port)
    if oper is None:
        return
    for key, value in oper.items():
        metric_data = f'{mongo_operation_metrics_name}{key}{{instanceId="{id}" ,resourceName="{name}", role="{role}"}} {value}'
        prometheus_push(prometheus_url, metric_data)


def mongo_response_monitor_all(mongo_info_list):
    """Monitors all PostgreSQL instances listed in mongo_info_list."""
    for mongo_info in mongo_info_list:
        try:
            logging.info(f"Start monitoring {mongo_info}")
            mongo_response_monitor(mongo_info)
        except Exception as e:
            traceback.print_exc()


def main():
    mongo_info_list = get_mongo_resource_info()
    mongo_response_monitor_all(mongo_info_list)


if __name__ == "__main__":
    main()
